import 'dart:convert';
import 'dart:io';
import 'package:book_manager_app/app/utils/widget/my_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:sn_progress_dialog/progress_dialog.dart';
import 'package:sn_progress_dialog/sn_progress_dialog.dart';
import 'package:url_launcher/url_launcher.dart';
import '../common/app_manager.dart';
import '../common/const.dart';
import '../common/sring_utils.dart';
import 'app_version_info.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';





class AppVersionManager {

  static String appName = "";
  static String packageName = "";
  static String version = "";
  static String buildNumber = "";

  // 获取 app 版本信息
  static init() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    appName = packageInfo.appName;
    packageName = packageInfo.packageName;
    version = packageInfo.version;
    buildNumber = packageInfo.buildNumber;
    debugPrint("AppVersionManager.init() 执行完毕！");
    debugPrint("AppName：$appName");
    debugPrint("packageName：$packageName");
    debugPrint("version：$version");
    debugPrint("buildNumber：$buildNumber");
  }

  /// 检查版本号
  static void checkVersionUpdate() async {
    AppVersionInfo? version;
    if (Platform.isIOS) version = await _iOSAppVersion();
    if (Platform.isAndroid) version = await _androidAppVersion();
    if (version != null) compareToUpdate(version);
  }


  /// 从 App Store 获取 iOS 的版本信息
  static Future<AppVersionInfo?> _iOSAppVersion() async {
    final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    final url = "$iOSVersionLookupURL?id=$iOSAppStoreID&timestamp=$timestamp";
    // 用GET方法请求，GET请求会有缓存，导致获取版本不及时，换为POST
    // 拼接时间戳，防止服务器对请求进行对 get 请求做缓存处理，或者使用 post 请求。
    final response = await http.post(Uri.parse(url));
    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      if (data is Map<String, dynamic>) {
        return AppVersionInfo.fromIOSAppStore(data);
      }
    }
    return null;
  }


  /// 获取 Android 的版本信息
  /// 优先使用品牌厂商内的应用商店更新
  /// 如果能针对设备品牌获取商店的版本号，跳转各自品牌厂商的应用商店更新App
  /// 如果商店没有上架，或者获取失败，则择使用 App 后台的服务器进行获取下载更新
  static Future<AppVersionInfo?> _androidAppVersion() async {
    //暂时只是从服务器获取uri链接取出最后数字做对比。
    // await LaunchRequest.androidAppUpdateInfo();
    return await _requestAppVersion();
    // switch (AppManager.brand) {
    //   case "Xiaomi":
    //   // 小米的逻辑处理
    //   // 目前，小米应用商店没有公开的官方 API，因此常见的方法是解析商店网页返回的 HTML 来获取版本信息。
    //     // xiaomiStoreVersion();
    //     break;
    //   case "Huawei":
    //   // 华为的逻辑处理
    //     break;
    // // 可以添加更多的 case 处理其他品牌
    //   default:
    //   // 默认处理逻辑，如果需要的话
    //     break;
    // }
    // return null;
  }


  /// 从[e车联后台systemConfig接口服务器]获取 App 版本apk之前的数字
  static Future<AppVersionInfo?> _requestAppVersion() async {
    // final appVersionInfo = await LaunchRequest.androidAppUpdateInfo();
    // return appVersionInfo;
    return null;
  }

  // 打开android的应用商店
  static openAndroidMarket() async {
    if (Platform.isAndroid) {
      final brand = AppManager.brand;
      String url = marketAndroid;
      if (brand == "Xiaomi") url = xiaomiMarket;
      if (brand == "Huawei") url = huaweiMarket;
      Uri uri = Uri.parse(url);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri);
      } else {
        throw '打开应用商店失败';
      }
    }
  }


  /// 打开 iOS 版 App Store
  static openIOSAppStore() async {
    // const url = "https://itunes.apple.com/cn/app/$AppStoreID";
    // Uri uri = Uri(scheme: 'https', host: 'itunes.apple.com', path: '/cn/app/$AppStoreID');
    Uri uri = Uri.parse(iOSAppStoreURL);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      throw "打开商店失败";
    }
  }



  /// 对比版本号判断是否弹出更新提示
  static void compareToUpdate(AppVersionInfo systemConfigVersion) {
    if(Platform.isIOS) {
      final localVersion = version;
      int state = systemConfigVersion.version.compareTo(localVersion);
      debugPrint("$appName iOS localVersion = $localVersion");
      debugPrint("$appName iOS storeVersion = ${systemConfigVersion.version}");
      if (state > 0) {
        showUpdateDialog(systemConfigVersion);
      }
    }else if(Platform.isAndroid){
      String localBuildNumber = buildNumber;
      if(StringUtils.notNullNorEmpty(localBuildNumber)&& StringUtils.notNullNorEmpty(systemConfigVersion.version)) {
        debugPrint("$appName Android localBuildNumber = $localBuildNumber");
        debugPrint("$appName Android storeVersion = ${systemConfigVersion.version}");
        if (int.parse(systemConfigVersion.version) >int.parse(localBuildNumber)) {
          showUpdateDialog(systemConfigVersion);
        }
      }
    }
  }

  /// 弹出更新的提示框
  static void showUpdateDialog(AppVersionInfo version) {
    if (AppManager.isShowUpload != true) {
      AppManager.isShowUpload = true;
      showAlertDialog(
        title: "检测到新版本",
        message: "是否升级到${version.version}版本？",
        margin: const EdgeInsets.only(left: 20, right: 20),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              child: RichText(
                text: TextSpan(children: [
                  TextSpan(
                    text: version.releaseNotes,
                    style: const TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
                  ),
                ]),
              ),
            ),
          ],
        ),
        confirmText: "立即更新",
        cancelText: "以后再说",
        buttonVertical: true,
        confirm: () async {
          dismissAlertDialog();
          AppManager.isShowUpload = false;
          if (Platform.isIOS) openIOSAppStore();
          if (Platform.isAndroid) openAndroidMarket();
        },
        cancel: () {
          dismissAlertDialog();
          AppManager.isShowUpload = false;
        },
      );
    }
  }

  /// 弹出更新的提示框
  static void showUpdateDialogAndroid(AppVersionInfo version, ProgressDialog progressDialogAndroid) {
    if (AppManager.isShowUpload != true) {
      AppManager.isShowUpload = true;
      showAlertDialogThreeButton(
        title: "检测到新版本",
        message: "是否升级到${version.version}版本？",
        margin: const EdgeInsets.only(left: 20, right: 20),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              child: RichText(
                text: TextSpan(children: [
                  TextSpan(
                    text: version.releaseNotes,
                    // text: "1. 新增了优惠券批量审核的功能\n2. 重构了客户关怀界面xxxx
                    style: const TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
                  ),
                ]),
              ),
            ),
          ],
        ),
        confirmText: "应用市场更新",
        middleText: "下载",
        cancelText: "以后再说",
        buttonVertical: true,
        confirm: () async {
          dismissAlertDialog();
          AppManager.isShowUpload = false;
          if (Platform.isAndroid) openAndroidMarket();
        },
        middle:() {
          dismissAlertDialog();
          AppManager.isShowUpload = false;
          _downLoader(Get.context!, version.downloadUrl, progressDialogAndroid);
      },
        cancel: () {
          dismissAlertDialog();
          AppManager.isShowUpload = false;
        },
      );
    }
  }





  // 下载 apk
  static Future<void> _downLoader(BuildContext context, String downLoadUrl, ProgressDialog progressDialogAndroid) async {
    try {
      String? dirPath = (await getApplicationDocumentsDirectory()).absolute.path;
      final savedDir = Directory(dirPath);
      if (!savedDir.existsSync()) {
        await savedDir.create();
      }
      String fileName = downLoadUrl.substring(downLoadUrl.lastIndexOf('/') + 1);
      String? taskIdMy = await FlutterDownloader.enqueue(
        url: downLoadUrl,
        savedDir: savedDir.path,
        showNotification: true,
        saveInPublicStorage: false,
        fileName: fileName,
        // show download progress in status bar (for Android)
        openFileFromNotification: true, // click on notification to open downloaded file (for Android)
      );

      // 如果在外部，取消或者暂停下载用到，
      localStorageWrite("taskId", taskIdMy);
      localStorageWrite("apkName", fileName);

      progressDialogAndroid.show(
          max: 100,
          msg: "新版本下载中",
          progressBgColor: Colors.green,
          progressType: ProgressType.valuable,
          // progressType: ProgressDialogType.download,
          cancel: Cancel(
            cancelClicked: () async {
              progressDialogAndroid.close();
              await FlutterDownloader.remove(taskId: taskIdMy!, shouldDeleteContent: true);
            },
          ),
          completed: Completed(
              completedMsg: "下载完成",
              //completedImage:  const AssetImage("images/green_selected.png"),//自定义完成图片
              completionDelay: 2500
          ));

    } catch (e) {
      debugPrint(e.toString());
    }
  }



}